import asyncio
import aiomysql
from app.db.models import Base
from app.db.session import engine
from app.core.config import settings

async def create_database():
    """创建数据库"""
    conn = await aiomysql.connect(
        host=settings.MYSQL_HOST,
        user=settings.MYSQL_USER,
        password=settings.MYSQL_PASSWORD,
    )
    async with conn.cursor() as cur:
        await cur.execute(
            f"CREATE DATABASE IF NOT EXISTS {settings.MYSQL_DB} "
            "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
        )
    conn.close()

async def create_tables():
    """创建表"""
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

async def init_db():
    """初始化数据库和表"""
    await create_database()
    await create_tables()
    print("数据库和表创建成功！")

if __name__ == "__main__":
    asyncio.run(init_db())